package com.lanmao.blog.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.lanmao.blog.utils.R;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class OssController {
    private String endpoint="oss-cn-shenzhen.aliyuncs.com";
    private String bucketName="edu-lanmao";
    private String accessId="LTAI4GK9fsbXNAeyDZbv44EP";
    private String  accessKeySecret="H0ZPDlwtuZLSfbmHlF7035jB93qxsB";
    @PostMapping("/oss/uploadOssFile")
    public String uploadOssFile(@RequestParam("file") MultipartFile file) {
        // 工具类获取值
        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            // yuy76t5rew01.jpg
            fileName = uuid+fileName;
            //2 把文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath+"/"+fileName;
            //调用oss方法实现上传
            //第一个 Bucket名称 第二个 上传到oss文件路径和文件名称 aa/bb/1.jpg  第三个 上传文件输入流
            ossClient.putObject(bucketName,fileName , inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
